//########################################################################
//## (C) by Edwin Vriethoff under Microsoft Reciprocal License (Ms-RL)  ##
//## See http://www.codeplex.com/SPUserPoll/license for full license    ##
//##                                                                    ##
//## http://edwin.vriethoff.net http://www.codeplex.com/SPUserPoll/     ##
//########################################################################

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using System.Web.UI.WebControls.WebParts;

namespace SPUserPoll.Data.Components
{
    /// <summary>
    /// Code library to manage webparts on the page
    /// </summary>
    public class WebParts
    {
        /// <summary>
        /// Alters the webpart 'data' properties on a page
        /// </summary>
        /// <param name="pageUrl"></param>
        /// <param name="webPartID"></param>
        /// <param name="propertyName"></param>
        /// <param name="propertyValue"></param>
        public void AlterProperty(string pageUrl, string webPartID, string propertyName, object propertyValue)
        {
            //leave this function if webpartID = null. For example the webpart preview gives a null value for the webpart
            if (webPartID == null)
                return;

            SPWeb web = SPContext.Current.Web; //don't dispose this object as it is the spcontext object!
            SPFile page = web.GetFile(pageUrl);

            SPLimitedWebPartManager limitedWebPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared);
            System.Web.UI.WebControls.WebParts.WebPart wp = limitedWebPartManager.WebParts[webPartID];
            wp.GetType().GetProperty(propertyName).SetValue(wp, propertyValue, null);
            limitedWebPartManager.SaveChanges(wp);
        }
    }
}
